<template>
	<view style="padding-bottom: 160rpx;">
		<u-navbar :customBack="backToList" v-if="!$isWeixin()" :title="ApplyForType == 2 ? '关停' : '并转'" :titleBold="true"></u-navbar>

		<u-tabs :list="tabList" active-color="#FF7A23" :current="tabIndex" @change="onTabChange"></u-tabs>

		<view v-show="tabIndex === 0" class="">
			<u-cell-group disabled>
				<u-cell-item title="申请类型" :arrow="false">
					<text v-if="ApplyForType == 2">关停</text>
					<text v-if="ApplyForType == 3">并转</text>
				</u-cell-item>

				<u-cell-item v-if="ApplyForType == 2" title="申请原因" :arrow="false">
					<u-radio-group disabled  v-model="form.ApplyForReasonId">
						<view class="grid-2">
							<u-radio v-for="(item, index) in DataBaseInfo.DealerShutDown_BaseList" :key="index" :name="item.Key">{{ item.Value }}</u-radio>
						</view>
					</u-radio-group>
				</u-cell-item>

				<u-cell-item v-if="ApplyForType == 3" title="申请原因" :arrow="false">
					<u-radio-group disabled v-model="form.ApplyForReasonId" @change="onShiftReasonChange">
						<view class="grid-2">
							<u-radio v-for="(item, index) in DataBaseInfo.DealerAndGoReason_BaseList" :key="index" :name="item.Key">{{ item.Value }}</u-radio>
						</view>
					</u-radio-group>
				</u-cell-item>

				<u-cell-item :arrow="false" title="迁移父级" v-if="form.ApplyForReasonId == 20 || form.ApplyForReasonId == 17 || form.ApplyForReasonId == 19">
					<u-input
						disabled
						:value="currentLevel1 && currentLevel1.Value"
						inputAlign="right"
						:selectOpen="showLevel1"
						placeholder="请选择父级"
					></u-input>
				</u-cell-item>

				<u-cell-item :arrow="false" title="迁移子集" v-if="form.ApplyForReasonId == 20">
					<u-input
						disabled
						:value="currentLevel2 && currentLevel2.Value"
						inputAlign="right"
						:selectOpen="showLevel2"
						placeholder="请选择子级"
					></u-input>
				</u-cell-item>

				<u-cell-item title="其他备注" :arrow="false" v-if="form.ApplyForReasonId == 10">
					<u-input disabled type="textarea" placeholder="其他备注" inputAlign="right" v-model="form.OtherNote"></u-input>
				</u-cell-item>

				<u-cell-item :arrow="false" title="申请时间">
					<u-input
						:value="$u.date(form.Date * 1000, 'yyyy-mm-dd')"
						inputAlign="right"
						placeholder="请选择"
						disabled
						@click="showTimePick = true"
						:selectOpen="showTimePick"
					></u-input>
					<u-picker
						:default-time="$u.date(form.Date * 1000, 'yyyy-mm-dd')"
						@confirm="onTimePickerChange"
						v-model="showTimePick"
						mode="time"
						:params="{ year: true, month: true, day: true, hour: false, minute: false, second: false }"
					></u-picker>
				</u-cell-item>

				<u-cell-item title="申请备注" :arrow="false"><u-input type="textarea" inputAlign="right" v-model="form.Remark" placeholder="申请备注"></u-input></u-cell-item>
			</u-cell-group>


			<view class="btn-group-fixed u-p-t-30 u-flex">
				<u-button @click="$u.route({ type: 'back' })">返回列表</u-button>
			</view>

			<u-select :default-value="[level1Index]" @confirm="onLevelChange($event, 1)" v-model="showLevel1" :list="level1List" value-name="Key" label-name="Value"></u-select>

			<u-select :default-value="[level2Index]" @confirm="onLevelChange($event, 2)" v-model="showLevel2" :list="level2List" value-name="Key" label-name="Value"></u-select>
		</view>

		<view v-show="tabIndex === 1" class="">
			<u-cell-group :border="false">
				<u-cell-item
					:border-bottom="ShowLevel == 3"
					v-if="ShowLevel == 2 || ShowLevel == 3"
					title="一级经销商名称"
					:arrow="false"
					:value="First_Dealer_BaseInfo.Name"
				></u-cell-item>
				<u-cell-item :border-bottom="false" v-if="ShowLevel == 3" title="二级经销商名称" :arrow="false" :value="Double_Dealer_BaseInfo.Name"></u-cell-item>

				<basic-information-form v-show="ShowLevel != 3" :loadCity="loadCity" :level="ShowLevel" ref="basicForm" :metadata="DataBaseInfo"></basic-information-form>

				<store-information-form v-show="ShowLevel == 3" :loadCity="loadCity" ref="storeForm"></store-information-form>
			</u-cell-group>
		</view>
		
		<u-toast ref="uToast" />
	</view>
</template>

<script>
export default {
	data() {
		return {
			tabList: [{ name: '渠道信息调整' }, { name: '基本信息' }],
			tabIndex: 0,

			ShowLevel: null,
			ApplyForType: 1,
			Id: '',
			loadCity: false,

			DataBaseInfo: {
				BusinessCategory_BaseList: [],
				CompetingGoodsBrandA_BaseList: [],
				CompetingGoodsBrandB_BaseList: [],
				CompetingGoodsBrandC_BaseList: [],
				DealerApplyFor_BaseList: [],
				DealerGrade_BaseList: [],
				DealerMaterialRequirements_BaseList: [],
				DealerShutDown_BaseList: [],
				DealerType_BaseList: [],
				DealerAndGoReason_BaseList: []
			},

			First_Dealer_BaseInfo: {},
			Double_Dealer_BaseInfo: {},
			Door_Dealer_BaseInfo: {},
			This_Dealer_OtherInfo: {},
			This_Dealer_RelationList: [],

			ThisDealerInfo: {
				Dealer_BaseInfo: {
					Account: '',
					Address: '',
					CityId: 610100,
					Created: 1460613600,
					DealerId: 114,
					Delivery_Address: '',
					Delivery_CityId: 610100,
					Delivery_DistrictId: 659020,
					Delivery_ProvinceId: 610000,
					DistrictId: 659020,
					IsFictitious: 0,
					KeDealerNo: '01000090',
					Level: 1,
					LevelName: '',
					Mobile: '',
					Name: '',
					NickName: '',
					Parent_DealerId: 90,
					Parent_Name: '',
					ProvinceId: 610000,
					Referred: '',
					State: 4,
					Telephone: ''
				},
				Dealer_OtherInfo: {
					BlessingNote: '',
					BossBirthday: 1626192000,
					BossName: '',
					BossPhone: '',
					BusinessCategory: '',
					BusinessLicenseA: '',
					CompetingGoodsBrandA: '',
					CompetingGoodsBrandB: '',
					CompetingGoodsBrandC: '',
					DealerGrade: 1,
					DealerType: 1,
					IsSign: 2,
					IsVIP: 1,
					LastYearsBDRSales: 14001,
					PeopleNum: 25,
					PercentageBDRSales: 35,
					TotalSales: 40001,
					TreatyPhoto: 'o_1ed682sou1iuf2lmc37rc31jjjd.png',
					TreatyPhotoType: 1
				},
				Dealer_RelationList: []
			},

			showTimePick: false,

			/**
			 * 并转原因 (并转功能页面才有) 注意 这里互动效果为：
			 * ①降成二级+变更所属一级 出现迁移父级一个搜索下拉   √
			 * ②升成一级 不出现下拉框												√
			 * ③变更所属二级 出现迁移父级 + 子级 2个搜索下拉框	√
			 * ④ 父级下拉框 代表Level=1 子集代表Level=2 在下拉搜索接口：PostDealerDic 的时候会用到
			 */
			showLevel1: false,
			level1List: [],
			level1Index: -1,
			currentLevel1: null,
			showLevel2: false,
			level2List: [],
			level2Index: -1,
			currentLevel2: null,

			form: {
				Id: '',
				AuditRemark: '',
				State: '',
				// 点击列表进入的经销商ID
				DealerId: null,
				// 申请类型 1.新增
				ApplyForType: 1,
				// 申请原因 主原因
				ApplyForReasonId: null,
				// 申请原因 次原因 （选了物料需求或者费用需求之后互动的 复选） 比如 12,13,14
				Requirements: '',
				// 其他备注 勾选申请/关停/并转原因中的其他选项 会出现其他备注 这里就是其他备注 （这个和申请备注不是一个字段噢 别搞错了）
				OtherNote: '',
				// 并转父级经销商ID 并转才传
				ParentId: null,
				// 并转子集经销商 并转才传
				AndGoSecondId: null,
				// 申请/关停/并转时间
				Date: parseInt(new Date().getTime() / 1000),
				// 申请/关停/并转备注
				Remark: ''
			}
		};
	},

	onLoad(options) {
		if (options.DealerId) {
			this.form.DealerId = options.DealerId;
		}
		if (options.ApplyForType) {
			this.ApplyForType = options.ApplyForType;
			this.form.ApplyForType = options.ApplyForType;
		}
		if (options.Id) {
			this.Id = options.Id;
			this.form.Id = options.Id;
		}

		this.getData();

		if (this.$isWeixin()) {
			this.$setTitle(this.title);
		}
	},

	methods: {
		backToList() {
			uni.navigateTo({
				url: '/pages/home/home'
			});
		},

		onTabChange(index) {
			this.tabIndex = index;
		},
		onTimePickerChange(e) {
			this.form.Date = new Date(`${e.year}-${e.month}-${e.day}`).getTime() / 1000;
		},
		onRequirementsChange(e) {
			this.form.Requirements = e.toString();
		},

		onShiftReasonChange(e) {
			this.resetLevel(1);
			this.resetLevel(2);
			if (e == 17 || e == 20 || e == 19) {
				this.getLevelList(1);
			} else {
			}
		},

		onLevelChange(e, level) {
			// 此处逻辑是为了解决打开下拉框后不做选择直接确定后不会选择第一项的问题
			let selected;
			if (!e[0].value || !e[0].label) {
				if (level == 1) {
					if (this.level1List.length > 0) {
						selected = {
							label: this.level1List[0].Value,
							value: this.level1List[0].Key
						};
					}
				}
				if (level == 2) {
					if (this.level2List.length > 0) {
						selected = {
							label: this.level2List[0].Value,
							value: this.level2List[0].Key
						};
					}
				}
			} else {
				selected = e[0];
			}

			if (level == 1) {
				this.currentLevel1 = selected;
				this.level1Index = this.level1List.findIndex(item => item.Key == e[0].value);
				this.form.ParentId = selected.value;

				this.getLevelList(2, selected.value);
				this.resetLevel(2);
			}
			if (level == 2) {
				this.currentLevel2 = selected;
				this.level2Index = this.level2List.findIndex(item => item.Key == e[0].value);
				this.form.AndGoSecondId = selected.value;
			}
		},

		// 重置下拉框相关属性
		// 比如: 选择了父级后重置子集列表及之前选中的子集选项.
		resetLevel(level) {
			if (level == 1) {
				this.currentLevel1 = null;
				this.level1Index = -1;
				this.level1List = [];
				this.form.ParentId = null;
			}

			if (level == 2) {
				this.currentLevel2 = null;
				this.level2Index = -1;
				this.level2List = [];
				this.form.AndGoSecondId = null;
			}
		},

		// 获取各等级下拉选项
		getLevelList(level, parentId, currentId) {
			this.$u.api
				.getDealerDic({
					Level: level,
					ParentId: parentId
				})
				.then(res => {
					const { ResultCode, ResultMessage, DealerList } = res;
					if (level == 1) {
						this.level1List = DealerList;

						if (currentId) {
							this.level1Index = DealerList.findIndex(item => item.Key == currentId);
							this.currentLevel1 = DealerList.find(item => item.Key == currentId);
						}
					}
					if (level == 2) {
						this.level2List = DealerList;

						if (currentId) {
							this.level2Index = DealerList.findIndex(item => item.Key == currentId);
							this.currentLevel2 = DealerList.find(item => item.Key == currentId);
						}
					}
				});
		},

		onSubmit() {
			this.form = { ...this.form, ...this.$refs.reviewForm.form };

			console.log(this.form);

			if (!this.form.State) {
				this.$u.toast('请选择审核状态');
				return false;
			}

			this.$u.api.approvalCloseAndShift(this.form).then(res => {
				const { ResultCode, ResultMessage } = res;
				if (ResultCode == 1) {
					this.$refs.uToast.show({
						title: ResultMessage,
						back: true
					});
				}
			});
		},

		getData() {
			this.$u.api
				.getDealerChangeReviewDetail({
					AdjustmentId: parseInt(this.form.Id),
					ApplayTypeId: parseInt(this.form.ApplyForType),
					DealerId: parseInt(this.form.DealerId)
				})
				.then(res => {
					const {
						ResultCode,
						ResultMessage,
						ShowLevel,
						AuditDetail,
						First_Dealer_BaseInfo,
						Double_Dealer_BaseInfo,
						Door_Dealer_BaseInfo,
						This_Dealer_OtherInfo,
						This_Dealer_RelationList,
						DataBaseInfo,
						AndGoParentId_List,
						AndGoSecondId_List,
						AuditForList
					} = res;

					if (ResultCode === 1) {
						this.ShowLevel = ShowLevel;

						if (AuditDetail) {
							this.form.ApplyForReasonId = AuditDetail.ApplyForReasonId;
							this.form.OtherNote = AuditDetail.OtherNote;
							this.form.Remark = AuditDetail.Remake;

							if (AuditDetail.ApplyForReasonId == 17 || AuditDetail.ApplyForReasonId == 19 || AuditDetail.ApplyForReasonId == 20) {
								this.getLevelList(1, null, AuditDetail.AndGoParentId);

								if (AuditDetail.AndGoSecondId) {
									this.getLevelList(2, AuditDetail.AndGoParentId, AuditDetail.AndGoSecondId);
								}
							}
						}

						this.First_Dealer_BaseInfo = First_Dealer_BaseInfo;
						this.Double_Dealer_BaseInfo = Double_Dealer_BaseInfo;
						this.AuditForList = AuditForList;

						if (Door_Dealer_BaseInfo) {
							this.Door_Dealer_BaseInfo = Door_Dealer_BaseInfo;
						}
						this.This_Dealer_OtherInfo = This_Dealer_OtherInfo;
						this.This_Dealer_RelationList = This_Dealer_RelationList;
						this.DataBaseInfo = DataBaseInfo;
						// this.AndGoParentId_List = AndGoParentId_List;
						// this.AndGoSecondId_List = AndGoSecondId_List;

						if (ShowLevel == 1) {
							this.$refs.basicForm.initForm({
								Dealer_BaseInfo: First_Dealer_BaseInfo,
								Dealer_OtherInfo: This_Dealer_OtherInfo
							});
						}

						if (ShowLevel == 2) {
							this.DataBaseInfo.BusinessCategory_BaseList.forEach(item => {
								item.checked = This_Dealer_OtherInfo.BusinessCategory.split(',').indexOf(String(item.Key)) > -1;
							});
							this.DataBaseInfo.CompetingGoodsBrandA_BaseList.forEach(item => {
								item.checked = This_Dealer_OtherInfo.CompetingGoodsBrandA.split(',').indexOf(String(item.Key)) > -1;
							});
							this.DataBaseInfo.CompetingGoodsBrandB_BaseList.forEach(item => {
								item.checked = This_Dealer_OtherInfo.CompetingGoodsBrandB.split(',').indexOf(String(item.Key)) > -1;
							});
							this.DataBaseInfo.CompetingGoodsBrandC_BaseList.forEach(item => {
								item.checked = This_Dealer_OtherInfo.CompetingGoodsBrandC.split(',').indexOf(String(item.Key)) > -1;
							});

							this.$refs.basicForm.initForm({
								Dealer_BaseInfo: Double_Dealer_BaseInfo,
								Dealer_OtherInfo: This_Dealer_OtherInfo
							});
						}

						if (ShowLevel == 3) {
							this.$refs.storeForm.initForm({
								Dealer_BaseInfo: Door_Dealer_BaseInfo,
								Dealer_OtherInfo: This_Dealer_OtherInfo,
								DealerDetail_Audit: AuditDetail,
								AuditForList: AuditForList
							});
						}

						if (ShowLevel != 3) {
							this.DataBaseInfo.BusinessCategory_BaseList.forEach(item => {
								item.checked = This_Dealer_OtherInfo.BusinessCategory.split(',').indexOf(String(item.Key)) > -1;
							});
							this.DataBaseInfo.CompetingGoodsBrandA_BaseList.forEach(item => {
								if (This_Dealer_OtherInfo) {
									item.checked = This_Dealer_OtherInfo.CompetingGoodsBrandA.split(',').indexOf(String(item.Key)) > -1;
								} else {
									item.checked = false;
								}
							});
							this.DataBaseInfo.CompetingGoodsBrandB_BaseList.forEach(item => {
								if (This_Dealer_OtherInfo) {
									item.checked = This_Dealer_OtherInfo.CompetingGoodsBrandB.split(',').indexOf(String(item.Key)) > -1;
								} else {
									item.checked = false;
								}
							});
							this.DataBaseInfo.CompetingGoodsBrandC_BaseList.forEach(item => {
								if (This_Dealer_OtherInfo) {
									item.checked = This_Dealer_OtherInfo.CompetingGoodsBrandC.split(',').indexOf(String(item.Key)) > -1;
								} else {
									item.checked = false;
								}
							});
						}

						this.loadCity = true;
					}
				});
		}
	}
};
</script>

<style lang="scss"></style>
